from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth import authenticate
from rest_framework_simplejwt.tokens import RefreshToken

# Create your views here.
from superuser.models import SuperUser

class Login(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        if not all([username, password]):
            return Response({'status': 400, 'message': '参数不全'})
        user = authenticate(username=username, password=password)
        if not user:
            return Response({'status': 400, 'message': '用户名或密码错误'})
        refresh = RefreshToken.for_user(user)
        return Response({
            'status': 200,
            'message': '登录成功',
            'data': {
                'refresh': str(refresh),
                'token': str(refresh.access_token),
                'username': user.username,
                'id': user.id,
            }
        })
